/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Image, LayoutAnimation,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    UIManager,
    View
} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import TracePage from "../TracePage";
import OrderPayPage from "./OrderPayPage";
import I18n from "../../../res/language/i18n";
import CommonUtils from "../../../common/CommonUtils";
import AlertDialog from "../../../custom/AlertDialog";
import BasWebViewPage from "../../common/BasWebViewPage";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import ReturnGoodsPage from "../../order/returnGoods/ReturnGoodsPage";
import ReturnOrdersPage from "../../order/returnGoods/ReturnOrdersPage";

let clickTypes = {payNow: 'pay-now', returnGoods: 'returnGoods', comment: 'Comment order', returnList: 'returnList'};
export default class OrderDetail extends Component {

    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();

        this.state = {
            swap_amount: '',
            currencyCode: '',
            showDialog: false,
            alertVisible: false,
            isReplaceOrder: false,
        }
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                this.setState({
                    swap_amount: JSON.parse(result).swap_amount,
                    currencyCode: JSON.parse(result).currency_code,
                });
            });

        let orderData = this.props.orderData;
        if (orderData && orderData.return_type == 1 && orderData.replace_order_sn) {

            this.timer = setTimeout(() => {
                this.setState({
                    isReplaceOrder: true,
                });
                this.startAnimation();
                this.timer && clearInterval(this.timer)
            }, 350);

        }

    }

    /**
     * 动画效果
     */
    startAnimation() {
        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental(true);
        }
        LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
    }


    /**地址信息Text*/
    getUserTv(addres) {
        let arrTv = [];
        if (addres !== null) {
            let split = addres.split('-');
            for (let i = 0; i < split.length; i++) {
                if (split[i] !== '') {
                    arrTv.push(
                        <Text style={[{marginTop: 10}, StyleUtils.smallFont]}>{split[i]}</Text>
                    )
                }
            }
        }
        return arrTv
    }

    /**产品信息Text*/
    getGoodsTv(goods) {
        let arrTv = [];
        for (let i = 0; i < goods.length; i++) {
            arrTv.push(
                <View style={[StyleUtils.flex, StyleUtils.center, StyleUtils.rowDirection, {height: 35}]}>
                    <Text numberOfLines={1}
                          style={[StyleUtils.flex, StyleUtils.smallTvColor, StyleUtils.smallFont]}>{goods && goods[i].goods_name ? goods[i].goods_name : null}</Text>
                    <Text numberOfLines={1}
                          style={[StyleUtils.flex, StyleUtils.smallTvColor, StyleUtils.smallFont, {textAlign: 'center'}]}>{goods && goods[i].goods_number ? goods[i].goods_number : null}</Text>
                    <Text numberOfLines={1}
                          style={[StyleUtils.flex, StyleUtils.smallTvColor, StyleUtils.smallFont, {textAlign: 'right'}]}>{(goods && goods[i].goods_amount ? goods[i].goods_amount * this.state.swap_amount : 0).toFixed(1) + this.state.currencyCode}</Text>
                </View>
            )
        }
        return arrTv
    }

    /**其他付款方式 0: '优惠券',1: '礼品卡',2: '积分卡'*/
    getOtherPay(otherPayType) {
        let otherPay;
        switch (otherPayType) {
            case 0:
                otherPay = I18n.t('default.coupons');
                break;
            case 1:
                otherPay = I18n.t('default.giftCard');
                break;
            case 2:
                otherPay = I18n.t('default.bonusCards');
                break;
            default:
                otherPay = I18n.t('default.coupons');
                break
        }
        return otherPay;
    }


    /**
     * 点击方法
     * @param type
     * */
    onClick(type) {
        let orderData = this.props.orderData;

        let _component = null;
        let _params = {};

        switch (type) {
            case clickTypes.returnList:
                _component = ReturnOrdersPage;
                _params = {
                    swap_amount: this.state.swap_amount,
                    currencyCode: this.state.currencyCode,
                };
                break;
            case clickTypes.returnGoods:
                _component = ReturnGoodsPage;
                _params = {
                    orderData,
                    swap_amount: this.state.swap_amount,
                    currencyCode: this.state.currencyCode,
                };
                break;
            case clickTypes.payNow:

                if (orderData.order_status >= 2) {
                    _component = BasWebViewPage;
                    _params = {uri: SERVER_TYPE.invoice + 'order_id=' + orderData.order_id};
                    break;
                }

                if (orderData.transaction_number !== null && orderData.pay_type === 'elsom' || orderData.pay_type === 'qiwi') {
                    this.showDialog(true);
                } else {
                    _component = OrderPayPage;
                    _params = {...this.props};
                }
                break;
            case clickTypes.comment:
                this.setState({
                    alertVisible: true,
                });

                break;
        }

        if (_component) {
            this.props.navigator.push({
                component: _component,
                name: _component + '',
                params: _params,
            });
        }

    }


    /**
     * 确认订单
     */
    confirmationOrder() {
        let orderData = this.props.orderData;

        CommonUtils.showLoading();

        this.setState({alertVisible: false});
        let formData = new FormData();
        formData.append('order_id', orderData.order_id);
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'finishOrder', formData)
            .then((result) => {
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    orderData.order_status = 88;
                    this.props.callBack && this.props.callBack(orderData);
                    this.props.navigator.pop();
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('OrderDetail---confirmationOrder--error:', error);
            });
    }


    render() {
        let orderData = this.props.orderData;
        let goods = orderData.goods;
        let elsomOPT = orderData.pay_type === 'elsom' ? 'OPT NO: ' : I18n.t('default.transactionId') + ': ';
        let state = this.state;
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}

                />
                <AlertDialog
                    visible={state.showDialog}
                    requestClose={() => this.showDialog(false)}
                    contentTv={I18n.t('default.completeYourPayment') + '\n' + I18n.t('default.orderNo') + ': ' + orderData.order_sn + '\n' + elsomOPT + orderData.transaction_number}
                    leftBtnOnclick={() => {
                        this.showDialog(false);
                        this.props.navigator.push({
                            component: OrderPayPage,
                            name: 'OrderPayPage',
                            params: {
                                ...this.props,
                            }
                        });
                    }}
                />
                <View style={StyleUtils.flex}>

                    <ScrollView>
                        <View style={[StyleUtils.flex, {padding: 16}]}>
                            {ViewUtils.getTitleView(I18n.t('default.orderDetail'), I18n.t('default.yorOrder') + orderData.order_sn)}

                            <View style={StyleUtils.lineStyle}/>

                            {ViewUtils.gitUserInformationTv(I18n.t('default.orderNo'), orderData.order_sn, '', () => {
                                this.props.navigator.push({component: TracePage, params: {orderId: orderData.order_id}})
                            }, I18n.t('default.trace'))}
                            {ViewUtils.gitUserInformationTv(I18n.t('default.orderDate'), orderData.add_time)}
                            {/*{ViewUtils.gitUserInformationTv('Order type:', orderData.order_type)}*/}
                            {ViewUtils.gitUserInformationTv(I18n.t('default.orderStatus'), new CommonUtils().orderStatus(orderData.order_status, orderData.return_type))}

                            {/*Deliver Details*/}
                            <Text
                                style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.deliverDetails')}</Text>

                            <Text style={[{marginTop: 16}, StyleUtils.smallFont]}>{orderData.consignee}</Text>
                            {this.getUserTv(orderData.address)}
                            <View style={StyleUtils.lineStyle}/>

                            {/*Order products*/}
                            <Text
                                style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.orderProducts')}</Text>

                            {this.getGoodsTv(goods)}

                            <View style={StyleUtils.lineStyle}/>
                            {/*Order total*/}
                            <Text style={[styles.defaultTv, StyleUtils.smallFont]}>{I18n.t('default.orderTotal')}</Text>

                            {ViewUtils.getDoubleTv(I18n.t('default.orderTotalAmount'), (orderData.goods_amount * state.swap_amount).toFixed(1) + state.currencyCode)}
                            {/*{ViewUtils.getDoubleTv(I18n.t('default.subtotal'), (orderData.full_order_amount || 0).toFixed(1) + state.currencyCode)}*/}
                            {ViewUtils.getDoubleTv(I18n.t('default.savings'), (orderData.discount_amount || 0).toFixed(1) + state.currencyCode)}
                            {ViewUtils.getDoubleTv(I18n.t('default.bonusPoints'), ((orderData.integral_amount || 0).toFixed()) + state.currencyCode)}
                            {ViewUtils.getDoubleTv(this.getOtherPay(orderData.othter_pay_type), ((orderData.other_pay_amount || 0).toFixed(1)) + state.currencyCode)}

                            {ViewUtils.getDoubleTv(I18n.t('default.vat'), (orderData.tax_amount * state.swap_amount || 0).toFixed(1) + state.currencyCode)}
                            {ViewUtils.getDoubleTv(I18n.t('default.importTaxIf'), (orderData.import_tax || 0).toFixed(1) + state.currencyCode)}
                            {ViewUtils.getDoubleTv(I18n.t('default.shippingCost'), (orderData.shipping_amount || 0).toFixed(1) + state.currencyCode)}
                            {/*{ViewUtils.getDoubleTv(I18n.t('default.serviceFee'), orderData.service_amount)}*/}
                            {/*<View style={[StyleUtils.flex, StyleUtils.center, StyleUtils.rowDirection, {marginTop: 16}]}>*/}
                            {/*<Text*/}
                            {/*style={[StyleUtils.flex, styles.total, StyleUtils.smallFont]}>{I18n.t('default.orderTotal')}</Text>*/}
                            {/*<Text*/}
                            {/*style={[StyleUtils.flex, styles.orderAmount, StyleUtils.smallFont]}>{(orderData.order_amount || 0).toFixed(1) + state.currencyCode}</Text>*/}
                            {/*</View>*/}

                            {/*{ViewUtils.getDoubleTv('Total', orderData.order_amount)}*/}

                            <View style={StyleUtils.lineStyle}/>

                            {/*Payment method*/}
                            <View style={[StyleUtils.justifySpace]}>

                                <Text
                                    style={[styles.defaultTv, StyleUtils.smallFont]}>
                                    {orderData.pay_type ? orderData.pay_type : I18n.t('default.payingAmount')}</Text>

                                <Text
                                    style={[styles.defaultTv, StyleUtils.smallFont]}>
                                    {(orderData.pay_amount || 0).toFixed(1) + state.currencyCode}</Text>

                            </View>


                            {orderData.return_status !== 1 && orderData.order_status !== 44 && ViewUtils.getButton(orderData.order_status >= 2 ? I18n.t('default.invoice') : I18n.t('default.payNow'), () => {
                                {
                                    this.onClick(clickTypes.payNow)
                                }

                            }, [StyleUtils.marginTop, StyleUtils.marginBottom])}

                            {orderData.order_status == 12 && ViewUtils.getButton(I18n.t('default.confirmationGoods'), () => this.onClick(clickTypes.comment), styles.cancelBtn, {color: '#333'})}
                            {/*Delete*/}
                            {orderData.is_lock !== 1 && orderData.order_status !== 44 && orderData.order_status >= 2 && !(orderData.order_status >= 21 && orderData.order_status <= 35) &&
                            ViewUtils.getButton(I18n.t('default.return'), () => this.onClick(clickTypes.returnGoods), [styles.cancelBtn, {marginTop: 16}], {color: '#333'})}

                            {orderData.order_status >= 21 && orderData.order_status <= 35 && ViewUtils.getButton(I18n.t('default.check'), () => this.onClick(clickTypes.returnList), [styles.cancelBtn,], {color: '#333'})}

                        </View>
                    </ScrollView>

                    <View style={{position: 'absolute', left: 0, right: 0}}>
                        {ViewUtils.renderOperationView(null, null, () => {
                                let ordersData = this.props.ordersData;
                                if (!ordersData) {
                                    return
                                }


                                let indexData = null;
                                for (let data of ordersData) {
                                    if (data.order_sn == orderData.replace_order_sn) {
                                        indexData = data;
                                        break;
                                    }
                                }

                                this.props.navigator.push({
                                    component: OrderDetail,
                                    params: {
                                        orderData: indexData,
                                        ordersData: this.props.ordersData,
                                    },
                                });


                            }, I18n.t('o.replaceOrderMsj'), '',
                            state.isReplaceOrder, true, false, '查看', true)}
                    </View>

                </View>
                <AlertDialog
                    contentTv={I18n.t('default.confirmationGoods')}
                    visible={state.alertVisible}
                    leftBtnOnclick={() => {
                        this.confirmationOrder();
                    }}
                    requestClose={() => {
                        this.setState({
                            alertVisible: false,
                        })
                    }}/>


            </View>)
    }

    /*alertDialog关闭*/
    showDialog(boolean) {
        this.setState({showDialog: boolean})
    }

}

const styles = StyleSheet.create({
    defaultTv: {
        marginTop: 16,
        fontSize: 18,
        color: 'black',
        textAlign: 'left'
    },
    orderAmount: {
        textAlign: 'right',
        color: '#343434',
        fontSize: 17
    },
    total: {
        color: '#202020',
        fontSize: 17,
        textAlign: 'left',
    },
    cancelBtn: {
        borderWidth: 1,
        backgroundColor: 'white',
        borderColor: '#4b4b4b'
    }
});

